<template>
  <div class="min-input-container">
    <el-input
      v-model="inputValue"
      :placeholder="placeholder"
      @change="handleChange"
      @input="handleInput"
    ></el-input>
    <p v-if="showCurrentValue" class="current-value">当前输入值: {{ inputValue }}</p>
    <div v-if="showResult" class="result-area">
      <el-alert
        v-if="error"
        :title="error"
        type="error"
        :closable="false"
      ></el-alert>
      <el-alert
        v-else-if="result !== null"
        :title="`最小值是: ${result}`"
        type="success"
        :closable="false"
      ></el-alert>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits } from 'vue';
import { minValue } from '../utils/minValue';
import 'element-plus/dist/index.css';

// 定义props
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '请输入数字，用逗号分隔（例如：1,2,3）'
  },
  autoCalculate: {
    type: Boolean,
    default: true
  },
  showResult: {
    type: Boolean,
    default: true
  },
  showCurrentValue: {
    type: Boolean,
    default: true
  }
});

// 定义emits
const emit = defineEmits(['update:modelValue', 'change', 'input', 'result', 'error']);

const inputValue = ref(props.modelValue);
const result = ref(null);
const error = ref(null);

// 监听props.modelValue的变化
watch(() => props.modelValue, (newValue) => {
  inputValue.value = newValue;
  if (props.autoCalculate) {
    calculateResult();
  }
});

// 监听inputValue的变化
watch(inputValue, (newValue) => {
  emit('update:modelValue', newValue);
});

const calculateResult = () => {
  error.value = null;
  
  if (!inputValue.value || !inputValue.value.trim()) {
    error.value = '请输入数字';
    emit('error', error.value);
    return;
  }
  
  try {
    // 将输入字符串转换为数字数组
    const numbers = inputValue.value.split(',').map(num => {
      const parsed = parseFloat(num.trim());
      if (isNaN(parsed)) {
        throw new Error(`"${num.trim()}"不是有效的数字`);
      }
      return parsed;
    });
    
    // 使用minValue函数计算最小值
    result.value = minValue(numbers);
    emit('result', result.value);
  } catch (err) {
    error.value = err.message;
    emit('error', error.value);
  }
};

const handleChange = () => {
  emit('change', inputValue.value);
  if (props.autoCalculate) {
    calculateResult();
  }
};

const handleInput = () => {
  emit('input', inputValue.value);
};
</script>

<style scoped>
.min-input-container {
  width: 100%;
}

.current-value {
  margin-top: 5px;
  font-size: 14px;
  color: #606266;
}

.result-area {
  margin-top: 10px;
}
</style>